<?php
/**
 * Jishupu-Laravel-Vue-Admin
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Http\Controllers;

use App\Http\Requests\InfoPageRequest;
use App\Http\Resources\InfoPageResource;
use App\Models\InfoCategory;
use App\Models\InfoPage;
use App\Services\AttachmentService;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * 信息单页功能模块
 * Class InfoPageController
 * @package App\Http\Controllers
 */
class InfoPageController extends Controller
{

    /**
     * 不存在单页时创建
     * @param InfoCategory $info_category
     * @return InfoPage
     */
    private function newInfoPage(InfoCategory $info_category)
    {
        if ($info_category->type != 3) {
            throw new NotFoundHttpException();
        }
        $info_page = InfoPage::find($info_category->id);
        if (!$info_page) {
            $info_page = new InfoPage();
            $info_page->info_category_id = $info_category->id;
            $info_page->title = $info_category->name;
            $info_page->save();
        }
        return $info_page;
    }

    /**
     * 查看
     * @param InfoCategory $info_category
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(InfoCategory $info_category)
    {
        $get_info_page = $this->newInfoPage($info_category);
        $result = InfoPageResource::make($get_info_page)->toArray(null);
        return $this->success('', $result);
    }

    /**
     * 修改
     * @param InfoCategory $info_category
     * @param InfoPageRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function update(InfoCategory $info_category, InfoPageRequest $request)
    {
        $data = $request->validate('update');
        $info_page = $this->newInfoPage($info_category);
        if (!$info_page->update($data)) return $this->errorUpdated();
        // 绑定附件
        AttachmentService::bind($info_page, 'cover_image', $info_page->cover_image);
        return $this->successUpdated();
    }
}
